<template>
  <Modal
    :title="permission ? '编辑权限' : '创建权限'"
    size="md"
    @close="$emit('close')"
  >
    <form @submit.prevent="handleSubmit" class="space-y-6">
      <!-- 权限名称 -->
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-2">
          权限名称 <span class="text-red-500">*</span>
        </label>
        <input
          v-model="form.name"
          type="text"
          placeholder="请输入权限名称"
          class="input w-full"
          :class="{ 'border-red-500': errors.name }"
          required
        >
        <p v-if="errors.name" class="mt-1 text-sm text-red-600">{{ errors.name }}</p>
      </div>

      <!-- 权限描述 -->
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-2">
          权限描述 <span class="text-red-500">*</span>
        </label>
        <textarea
          v-model="form.description"
          placeholder="请输入权限描述"
          rows="3"
          class="input w-full resize-none"
          :class="{ 'border-red-500': errors.description }"
          required
        />
        <p v-if="errors.description" class="mt-1 text-sm text-red-600">{{ errors.description }}</p>
      </div>

      <!-- 权限分类 -->
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-2">
          权限分类 <span class="text-red-500">*</span>
        </label>
        <div class="space-y-2">
          <select
            v-model="form.category"
            class="input w-full"
            :class="{ 'border-red-500': errors.category }"
            required
          >
            <option value="">请选择分类</option>
            <option v-for="category in categories" :key="category" :value="category">
              {{ category }}
            </option>
            <option value="__custom__">自定义分类</option>
          </select>
          
          <!-- 自定义分类输入 -->
          <div v-if="form.category === '__custom__'">
            <input
              v-model="customCategory"
              type="text"
              placeholder="请输入新分类名称"
              class="input w-full"
              :class="{ 'border-red-500': errors.customCategory }"
              @blur="handleCustomCategory"
            >
            <p v-if="errors.customCategory" class="mt-1 text-sm text-red-600">{{ errors.customCategory }}</p>
          </div>
        </div>
        <p v-if="errors.category" class="mt-1 text-sm text-red-600">{{ errors.category }}</p>
      </div>

      <!-- 权限代码 -->
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-2">
          权限代码
        </label>
        <input
          v-model="form.code"
          type="text"
          placeholder="例如：user:create, user:edit"
          class="input w-full"
          :class="{ 'border-red-500': errors.code }"
        >
        <p class="mt-1 text-sm text-gray-500">
          权限代码用于程序中的权限判断，建议使用英文和冒号格式
        </p>
        <p v-if="errors.code" class="mt-1 text-sm text-red-600">{{ errors.code }}</p>
      </div>

      <!-- 权限级别 -->
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-2">
          权限级别
        </label>
        <div class="grid grid-cols-3 gap-3">
          <label
            v-for="level in permissionLevels"
            :key="level.value"
            class="flex items-center p-3 border rounded-lg cursor-pointer hover:bg-gray-50"
            :class="{
              'border-blue-500 bg-blue-50': form.level === level.value,
              'border-gray-300': form.level !== level.value
            }"
          >
            <input
              v-model="form.level"
              type="radio"
              :value="level.value"
              class="sr-only"
            >
            <div class="flex items-center">
              <i :class="[level.icon, 'w-5 h-5 mr-2', level.color]" />
              <div>
                <div class="text-sm font-medium">{{ level.label }}</div>
                <div class="text-xs text-gray-500">{{ level.description }}</div>
              </div>
            </div>
          </label>
        </div>
      </div>

      <!-- 依赖权限 -->
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-2">
          依赖权限
        </label>
        <div class="space-y-2">
          <div class="flex items-center justify-between">
            <span class="text-sm text-gray-600">选择此权限需要的前置权限</span>
            <button
              type="button"
              @click="showDependencies = !showDependencies"
              class="text-sm text-blue-600 hover:text-blue-800"
            >
              {{ showDependencies ? '收起' : '展开' }}
            </button>
          </div>
          
          <div v-if="showDependencies" class="max-h-40 overflow-y-auto border rounded-lg p-3 space-y-2">
            <label
              v-for="dep in availableDependencies"
              :key="dep.id"
              class="flex items-center"
            >
              <input
                v-model="form.dependencies"
                type="checkbox"
                :value="dep.id"
                class="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
              >
              <span class="ml-2 text-sm">{{ dep.name }}</span>
            </label>
          </div>
        </div>
      </div>
    </form>

    <template #footer>
      <div class="flex justify-end space-x-3">
        <button
          type="button"
          @click="$emit('close')"
          class="btn-secondary"
        >
          取消
        </button>
        <button
          @click="handleSubmit"
          :disabled="loading"
          class="btn-primary"
        >
          <i v-if="loading" class="w-4 h-4 mr-2 animate-spin mdi:loading" />
          {{ permission ? '更新' : '创建' }}
        </button>
      </div>
    </template>
  </Modal>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import Modal from '@/components/Modal.vue'

interface Permission {
  id: string
  name: string
  description: string
  category: string
  code?: string
  level?: string
  dependencies?: string[]
}

interface Props {
  permission?: Permission | null
  categories: string[]
}

interface Emits {
  (e: 'close'): void
  (e: 'save', data: Partial<Permission>): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const loading = ref(false)
const showDependencies = ref(false)
const customCategory = ref('')

// 表单数据
const form = reactive({
  name: '',
  description: '',
  category: '',
  code: '',
  level: 'normal',
  dependencies: [] as string[]
})

// 表单验证错误
const errors = reactive({
  name: '',
  description: '',
  category: '',
  code: '',
  customCategory: ''
})

// 权限级别选项
const permissionLevels = [
  {
    value: 'low',
    label: '低级',
    description: '基础权限',
    icon: 'mdi:shield-outline',
    color: 'text-green-500'
  },
  {
    value: 'normal',
    label: '普通',
    description: '常规权限',
    icon: 'mdi:shield',
    color: 'text-blue-500'
  },
  {
    value: 'high',
    label: '高级',
    description: '敏感权限',
    icon: 'mdi:shield-star',
    color: 'text-red-500'
  }
]

// 可用的依赖权限（模拟数据）
const availableDependencies = ref<Permission[]>([])

// 监听权限变化，初始化表单
watch(() => props.permission, (newPermission) => {
  if (newPermission) {
    form.name = newPermission.name
    form.description = newPermission.description
    form.category = newPermission.category
    form.code = newPermission.code || ''
    form.level = newPermission.level || 'normal'
    form.dependencies = newPermission.dependencies || []
  } else {
    resetForm()
  }
}, { immediate: true })

// 重置表单
const resetForm = () => {
  form.name = ''
  form.description = ''
  form.category = ''
  form.code = ''
  form.level = 'normal'
  form.dependencies = []
  customCategory.value = ''
  clearErrors()
}

// 清除错误
const clearErrors = () => {
  errors.name = ''
  errors.description = ''
  errors.category = ''
  errors.code = ''
  errors.customCategory = ''
}

// 处理自定义分类
const handleCustomCategory = () => {
  if (customCategory.value.trim()) {
    form.category = customCategory.value.trim()
  }
}

// 验证表单
const validateForm = () => {
  clearErrors()
  let isValid = true

  if (!form.name.trim()) {
    errors.name = '请输入权限名称'
    isValid = false
  }

  if (!form.description.trim()) {
    errors.description = '请输入权限描述'
    isValid = false
  }

  if (!form.category || form.category === '__custom__') {
    if (form.category === '__custom__' && !customCategory.value.trim()) {
      errors.customCategory = '请输入自定义分类名称'
      isValid = false
    } else if (!form.category) {
      errors.category = '请选择权限分类'
      isValid = false
    }
  }

  if (form.code && !/^[a-zA-Z0-9:_-]+$/.test(form.code)) {
    errors.code = '权限代码只能包含字母、数字、冒号、下划线和横线'
    isValid = false
  }

  return isValid
}

// 提交表单
const handleSubmit = async () => {
  if (!validateForm()) {
    return
  }

  loading.value = true
  try {
    const submitData: Partial<Permission> = {
      name: form.name.trim(),
      description: form.description.trim(),
      category: form.category === '__custom__' ? customCategory.value.trim() : form.category,
      code: form.code.trim() || undefined,
      level: form.level,
      dependencies: form.dependencies.length > 0 ? form.dependencies : undefined
    }

    emit('save', submitData)
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载依赖权限数据
const loadDependencies = async () => {
  try {
    // 模拟API调用
    availableDependencies.value = [
      { id: '1', name: '用户查看', description: '', category: '用户管理' },
      { id: '2', name: '角色查看', description: '', category: '用户管理' },
      { id: '3', name: '系统查看', description: '', category: '系统管理' }
    ]
  } catch (error) {
    console.error('加载依赖权限失败:', error)
  }
}

onMounted(() => {
  loadDependencies()
})
</script>